<!--提交的表单数据管理-->
<template>
  <div id="businessFormValue" class="app-container  flex-row">
    <!-- 左侧树 -->
    <div class="conmmon-container-left scroll__y__content scrollbar-no-width" style="width:290px;">
      <div class="common-title">
        <h2>表单</h2>
      </div>
      <el-tree
        ref="elTree"
        style="margin:0"
        class="common-el-tree"
        :data="formTreeData"
        default-expand-all
        :props="{ children: 'children', label: 'label'}"
        node-key="id"
        :expand-on-click-node="false"
        @node-click="handleFromNodeClick">
        <span slot-scope="{ node,data }" class="custom-tree-node">
          <img v-if="data.icon" :src="global.getFileView(data.icon)" class="common-round-image-32" :title="node.label" style="margin-right: 4px; width: 22px;height: 22px;" @error="handleImageError">
          <span class="text">{{ node.label }}</span>
        </span>
      </el-tree><!---->
    </div>
    <div class="conmmon-container-main flex-main">
      <!--搜索条件-->
      <div class="filter-container">
        <el-form :model="listQuery" :inline="true">
          <el-form-item>
            <el-input v-model="listQuery.formName" disabled placeholder="请选择左侧某一节点" />
          </el-form-item>
          <el-form-item>
            <el-input v-model="listQuery.keyword" placeholder="请输入关键字" @keyup.enter.native="handleFilter" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" plain @click="handleFilter">搜索</el-button>
            <el-button icon="el-icon-refresh" plain @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!--列表-->
      <div class="table-container flex-main">
        <div class="table-container-header">
          <table-toolbar @create="handleCreate" @refresh="handleFilter" @remove="removeRecord">
            <template slot="rightTool">
              <export-drop-down class-name="businessFormValue" :list-query="listQuery" title="提交的表单数据" />
            </template>
          </table-toolbar>
        </div>
        <el-table
          ref="multipleTable"
          :data="list"
          header-cell-class-name="table-header"
          fit
          height="100%"
          highlight-current-row
          @selection-change="handleSelectionChange"
          @row-click="handleRowClick"
          @sort-change="sortChange">
          <el-table-column type="selection" width="60" />
          <el-table-column align="center" prop="id" label="#" width="60">
            <template slot-scope="scope">{{ scope.$index+1 }}</template>
          </el-table-column>
          <el-table-column label="表单" prop="gmtCreated" sortable min-width="300" show-overflow-tooltip>
            <template slot-scope="scope">
              <span class="color-primary common-cursor" @click="handleView(scope.row)">【{{ scope.row.createdBy | optionUserFormat }}】于&nbsp;&nbsp;{{ scope.row.gmtCreated | formatDate }}&nbsp;&nbsp;填写的【{{ listQuery.formName }}】</span>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" fixed="right" width="90">
            <template slot-scope="scope">
              <button-option icon="el-icon-edit" skin="primary" title="编辑" @click="handleUpdate(scope.row)" />
              <button-option icon="el-icon-delete" skin="danger" title="删除" @click="handleRemoveSingle(scope.row)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination_handler">
        <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />
      </div>
    </div>

    <!--新增/编辑侧边栏-->
    <side-box :show="sideBox.recordShow" :title="sideBox.title" @close="sideBox.recordShow = !sideBox.recordShow">
      <template slot="body">
        <div class="el-form-item">
          <label class="el-form-item__label" style="width: 125px;"><span>所属表单</span></label>
          <div class="el-form-item__content" style="margin-left: 125px;">
            <el-input v-model="businessFormValueRecord.formName" disabled show-word-limit placeholder="请输入" />
          </div>
        </div>
        <form-create
          ref="formCreater"
          v-model="formCreate"
          :rule="formCreaterRule"
          :option="formCreaterOption"
          :value="formCreaterValue" />
      </template>
      <template slot="foot">
        <el-button type="primary" plain @click="sideBox.status==='create'?createData():updateData()">保存 </el-button>
      </template>
    </side-box>

    <model-dialog
      title="表单数据详情"
      :visible.sync="sideBox.recordDetailsShow"
      width="600px"
      @close="sideBox.recordDetailsShow=!sideBox.recordDetailsShow">
      <div class="item flex-row" style="    margin-top: 15px;">
        <div style="font-weight: bold;">所属表单：</div>
        <div>{{ businessFormValueRecord.formName }}</div>
      </div>
      <div class="item flex-row" style="margin-top: 15px;">
        <div style="font-weight: bold;">填报者：</div>
        <div>{{ businessFormValueRecord.createdBy | optionUserFormat }}</div>
        <div style="font-weight: bold;margin-left:20px">填写时间：</div>
        <div>{{ businessFormValueRecord.gmtCreated | formatDate }}</div>
      </div>
      <div style="margin: 15px 0px;font-size:14px">表单明细如下：</div>
      <div v-for="(item,key) in formDetailsValues" :key="key" class="item flex-row" style="    margin-top: 15px;">
        <div style="font-weight: bold;">{{ key+1 }}、{{ item.title }}：</div>
        <div>
          <template v-if="item.type==='input'">
            {{ item.value }}
          </template>
          <template v-if="item.type==='upload'">
            <template v-if="item.value">
              <span v-for="(data,index) in item.value" :key="data" class="common-cursor color-primary" style="margin-right:10px" @click="lookUpload(data)">
                附件{{ index+1 }}
              </span>
            </template>
            <span v-else class="color-danger title">暂无{{ item.title }}</span>

          </template>
        </div>
      </div>
    </model-dialog>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
export default {
  components: {},

  data() {
    return {
      formTreeData: [],
      list: [],
      total: 0,
      listQuery: {
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      },

      multipleSelectionRecords: [],
      // 固定写法
      sideBox: {
        recordShow: false,
        title: '',
        status: 'create',
        recordDetailsShow: false
      },
      businessFormValueRecord: {},
      businessFormValueRules: {
        formId: [
          { required: true, message: '请输入表单', trigger: 'blur' }
        ],
        formValue: [
          { required: true, message: '请输入表单内容', trigger: 'blur' }
        ]
      },
      formDetailsValues: [],

      formCreate: null,
      formCreaterValue: {},
      formCreaterRule: [],
      formCreaterOption: {
        submitBtn: false,
        onSubmit: function(formData) {
        }
      }
    }
  },
  watch: {
    'listQuery.formId': function() {
      this.fetchData()
    }
  },
  created() {
    this.fetchFromTree()
  },
  methods: {
    fetchFromTree() {
      this.$store.dispatch('businessFormListTree').then((res) => {
        this.formTreeData = res
        if (this.formTreeData) {
          if (this.formTreeData[0].children) {
            this.handleFromNodeClick(this.formTreeData[0].children[0])
          }
        }
      }).catch((_) => {})
    },
    handleFromNodeClick(data) {
      if (data.ext === '2') {
        this.listQuery = {
          ...this.listQuery,
          formId: data.id,
          formName: data.label
        }
      }
    },
    // 表格自带方法开始
    /* 全选/反选*/
    handleSelectionChange(val) {
      this.multipleSelectionRecords = val
    },
    /* 表格行数据单击*/
    handleRowClick(row) {
      this.$refs.multipleTable.toggleRowSelection(row)
    },
    /* 表格列排序*/
    sortChange(data) {
      const { prop, order } = data
      if (prop) {
        if (order === 'ascending') {
          this.listQuery.sort = '+' + prop
        } else {
          this.listQuery.sort = '-' + prop
        }
      } else {
        this.listQuery.sort = this.common.SORT_DEFAULT
      }
      this.handleFilter()
    },
    // 表格自带方法结束

    /* 搜索*/
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    /* 重置*/
    handleReset() {
      this.listQuery = {
        ...this.listQuery,
        page: 1,
        limit: this.common.PAGE_LIMIT_DEFAULT,
        keyword: undefined,
        sort: this.common.SORT_DEFAULT
      }
      this.fetchData()
    },
    async fetchData() {
      const response = await this.$store.dispatch('businessFormValuePage', this.listQuery)
      this.list = response.records
      this.total = response.total
    },
    /* 新增*/
    handleCreate() {
      this.businessFormValueRecord = {}
      this.sideBox.status = 'create'
      this.sideBox.recordShow = true
      this.sideBox.title = '新增提交的表单数据'
      this.$nextTick(() => {
        this.$store.dispatch('businessFormGetDetailsById', this.listQuery.formId).then((res) => {
          this.businessFormValueRecord = {
            formName: res.name
          }
          if (res.formContent) {
            res.formContent = res.formContent.replaceAll('${fileServer}', this.$FILE_SERVER + 'file/upload?catalogId=' + this.constants.FILE_CATALOG_CUSTOM_FORM)
            res.formContent = res.formContent.replaceAll('${ProjectsId}', this.constants.PROJECTS_ID)
            res.formContent = res.formContent.replaceAll('${Access-Token}', getToken())
            this.formCreaterRule = JSON.parse(res.formContent)
          } else {
            this.formCreaterRule = []
            this.msgWarning('改表单暂未设置表单!')
          }
          console.log(res)
        })
      })
    },
    createData() {
      this.formCreate.validate((validate) => {
        if (validate) {
          this.formCreate.submit((formData) => {
            this.$store.dispatch('businessFormValueSave', {
              'formId': this.listQuery.formId,
              'formValue': JSON.stringify(formData)
            }).then(response => {
              this.sideBox.recordShow = false
              this.msgSuccess('新增成功')
              this.handleFilter()
            }).catch(() => {
              this.sideBox.recordShow = true
            })
          })
        }
      })
    },
    /* 编辑*/
    handleUpdate(row) {
      this.sideBox.status = 'update'
      this.sideBox.recordShow = true
      this.sideBox.title = '编辑提交的表单数据'
      this.$nextTick(() => {
        this.$store.dispatch('businessFormValueGetDetailsById', row.id).then((res) => {
          this.businessFormValueRecord = res.value
          if (res.form) {
            res.form = res.form.replaceAll('${fileServer}', this.$FILE_SERVER + 'file/upload?catalogId=' + this.constants.FILE_CATALOG_CUSTOM_FORM)
            res.form = res.form.replaceAll('${ProjectsId}', this.constants.PROJECTS_ID)
            res.form = res.form.replaceAll('${Access-Token}', getToken())
            this.formCreaterRule = JSON.parse(res.form)
            // 填充数据
            if (res.value.formValue) {
              var json = JSON.parse(res.value.formValue)
              var obj = {}
              for (var index in json) {
                obj[index] = json[index]
              }
              this.$nextTick(() => {
                this.formCreaterValue = obj
              })
            }
          } else {
            this.msgWarning('暂未设置提交表单')
            this.sideBox.recordShow = false
          }

        // this.$refs.formDesigner.setRule(JSON.parse(res.formContent))
        }).catch((_) => {})
      })
    },
    updateData() {
      this.formCreate.submit((formData) => {
        this.$store.dispatch('businessFormValueUpdate', {
          ...this.businessFormValueRecord,
          'formValue': JSON.stringify(formData)
        }).then(response => {
          this.sideBox.recordShow = false
          this.msgSuccess('修改成功')
          this.handleFilter()
        }).catch(() => {
          this.sideBox.recordShow = true
        })
      })
    },

    /* 删除*/
    handleRemoveSingle(row) {
      this.multipleSelectionRecords = []
      this.multipleSelectionRecords.push(row)
      this.$refs.multipleTable.clearSelection()
      this.$refs.multipleTable.toggleRowSelection(row, true)
      this.removeRecord()
    },
    removeRecord() {
      if (this.multipleSelectionRecords.length > 0) {
        const ids = []
        this.multipleSelectionRecords.forEach(function(v, i) {
          ids.push(v.id)
        })
        this.$confirm('此操作将永久删除记录, 是否继续?', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$store.dispatch('businessFormValueRemove', ids).then(response => {
            this.handleFilter()
            this.msgSuccess('删除成功')
          }).catch(() => {})
        }).catch(() => { })
      } else {
        this.msgWarning('请选择要删除的记录')
      }
    },
    handleView(row) {
      this.$store.dispatch('businessFormValueGetDetailsById', row.id).then((res) => {
        if (res.form) {
          this.sideBox.recordDetailsShow = true
          this.businessFormValueRecord = res.value
          var json = JSON.parse(res.value.formValue)
          var form = JSON.parse(res.form)
          var obj = {}
          for (var index in json) {
            obj[index] = json[index]
          }
          this.formDetailsValues = []

          for (var item of form) {
            this.formDetailsValues.push({
              title: item.title,
              value: obj[item.field],
              type: item.type
            })
          }
        }
      }).catch((_) => {})
    },
    lookUpload(uuid) {
      window.open(this.global.getFileView(uuid))
    }

  }
}
</script>
<style lang="scss" scoped>
</style>
